package utils;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by cwx183898 on 2017/5/27.
 */
public final class MD5Util {

    private static final Log LOG = LogFactory.getLog(MD5Util.class);

    private MD5Util() {
    }

    public static String encode(String src, String encoding) {
        StringBuffer sb = new StringBuffer(src);
        String reversedSrc = sb.reverse().toString();

        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(reversedSrc.getBytes(encoding));
            StringBuffer stringBuffer = new StringBuffer();
            for (byte b : bytes) {
                int bt = b & 0xff;
                if (bt < 16) {
                    stringBuffer.append(0);
                }
                stringBuffer.append(Integer.toHexString(bt));
            }
            return stringBuffer.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            LOG.error("加密字符串出现异常", e);
        } catch (UnsupportedEncodingException e) {
            LOG.error("加密字符串出现异常", e);
        }
        return null;
    }
}
